package meta.api.web.directory.presentation;

import java.util.ArrayList;
import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import meta.api.web.account.businessinfo.UserInfo;
import meta.api.web.common.util.ApiUtil;
import meta.api.web.directory.businesscontrol.DirMngBusiCtrl;
import meta.api.web.directory.businessinfo.DirInfo;
import meta.api.web.directory.presentation.form.DirForm;
import meta.api.web.directory.presentation.form.DirListResult;
import meta.common.log.CmnLogger;
import meta.common.msg.MessageConst;
import meta.common.util.JsonUtil;
import meta.common.util.ListUtil;
import meta.common.util.StrUtil;
import meta.common.util.WebUtil;

@Controller
@RequestMapping(value="api/directory")
@Tag(name = "文件夹管理机能", description = "文件夹管理机能")
public class DirMngController {

    private static final CmnLogger logger = CmnLogger.getLogger(DirMngController.class);

    private static final String FUNC_NM = "文件夹管理机能";

    private static final String DIR_TYPE_2D_COMP = "le5le2d-components";

    private static final String ERROR_MSG_DATA_ERROR= "请求数据错误";
    private static final String ERROR_MSG_GET_LIST_ERROR= "获取文件夹列表失败";
    private static final String ERROR_MSG_EXISTED_ERROR= "文件夹已经存在";
    private static final String ERROR_MSG_SAVE_ERROR= "保存文件夹失败";
    private static final String ERROR_MSG_UPDATE_ERROR= "更新文件夹失败";
    private static final String ERROR_MSG_GET_ERROR= "获取文件夹失败";
    private static final String ERROR_MSG_DELETE_ERROR= "删除文件夹失败";

    @Autowired
    private DirMngBusiCtrl dirMngBusiCtrl;

    /**
     * 获取组件(云盘)文件夹列表
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/list")
    @Operation(tags = "获取组件(云盘)文件夹列表", description = "获取组件(云盘)文件夹列表")
    public String list(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取组件(云盘)文件夹列表", null);

        DirForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), DirForm.class);
        if (inputdata == null
                || StrUtil.isEmpty(inputdata.getFullpath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        String type = judgeDirType(inputdata.getFullpath());
        if (StrUtil.isEmpty(type)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        int total;
        List<DirInfo> dirList= new ArrayList<DirInfo>();
        try {
            // 取得登录用户详细情报
            UserInfo loginUser = WebUtil.getLoginUser(req);

            // 获取数据总件数
            total = dirMngBusiCtrl.getDirTotal(loginUser.getId(), type, inputdata.getFullpath());

            // 获取数据列表
            if (total > 0) {
                dirList = dirMngBusiCtrl.getDirList(loginUser.getId(), type, inputdata.getFullpath());
            }

            DirListResult result = new DirListResult();
            result.setTotal(total);
            result.setList(dirList);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(result));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_LIST_ERROR);
        }

        return null;
    }

    /**
     * 添加组件(云盘)文件夹
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/add")
    @Operation(tags = "添加组件(云盘)文件夹", description = "添加组件(云盘)文件夹")
    public String add(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "添加组件(云盘)文件夹", null);

        DirForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), DirForm.class);
        if (inputdata == null
                || StrUtil.isEmpty(inputdata.getFullpath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        String type = judgeDirType(inputdata.getFullpath());
        if (StrUtil.isEmpty(type)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        // 检证是否已经存在文件夹
        if (dirMngBusiCtrl.checkExistDir(loginUser.getId(), type, inputdata.getFullpath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_EXISTED_ERROR);
            return null;
        }

        // 保存组件(云盘)文件夹
        try {
            dirMngBusiCtrl.saveDir(loginUser.getId(), type, inputdata.getFullpath());
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_SAVE_ERROR);
            return null;
        }

        // 获取组件(云盘)文件夹
        DirInfo dir = null;
        try {
            dir = dirMngBusiCtrl.getDir(loginUser.getId(), type, inputdata.getFullpath());
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_ERROR);
            return null;
        }

        if (dir == null) {
            ApiUtil.setNotFoundResponse(req, res);
        } else {
            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(dir));
        }
        return null;
    }

    /**
     * 更新组件(云盘)文件夹
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/update")
    @Operation(tags = "更新组件(云盘)文件夹", description = "更新组件(云盘)文件夹")
    public String update(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "更新组件(云盘)文件夹", null);

        DirForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), DirForm.class);
        if (inputdata == null
                || StrUtil.isEmpty(inputdata.getOldFullpath())
                || StrUtil.isEmpty(inputdata.getNewFullpath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        String type = judgeDirType(inputdata.getNewFullpath());
        if (StrUtil.isEmpty(type)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        // 更新组件(云盘)文件夹
        try {
            dirMngBusiCtrl.updateDir(loginUser.getId(), type,
                    inputdata.getOldFullpath(), inputdata.getNewFullpath());

            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_UPDATE_ERROR);
        }

        return null;
    }

    /**
     * 删除组件(云盘)文件夹
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/delete")
    @Operation(tags = "删除组件(云盘)文件夹", description = "删除组件(云盘)文件夹")
    public String delete(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "删除组件(云盘)文件夹", null);

        DirForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), DirForm.class);
        if (inputdata == null
                || ListUtil.isEmptyList(inputdata.getFullpaths())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        String type = judgeDirType(inputdata.getFullpaths().get(0));
        if (StrUtil.isEmpty(type)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        // 删除组件(云盘)文件夹
        try {
            dirMngBusiCtrl.deleteDir(loginUser.getId(), type, inputdata.getFullpaths());

            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETE_ERROR);
        }

        return null;
    }

    private String judgeDirType(String fullpath) {
        if (StrUtil.isEmpty(fullpath)) {
            return null;
        }
        if (fullpath.startsWith("/2D")) {
            return DIR_TYPE_2D_COMP;
        } else if (fullpath.startsWith("/3D/我的")) {
            String[] pathNodes = StrUtil.splitAll(fullpath, "/");
            return pathNodes[1] + "/" + pathNodes[2];
        } else if (fullpath.startsWith("/大屏")) {
            return "大屏";
        }
        return fullpath;
    }
}
